<?php
/**
 * 支付模块 接口
 * @author  jackzheng
 */


class payAction extends Action{

	/**
	 * 收银台 
	 * 返回可用支付方式
	 * @return [type] [description]
	 */
	public function cashier_desk(){
		GZ_Api::authToken();
        $user_id = _POST("user_id");
        $action_type	 = _POST("action_type");

        $money_list = array();

		//支付订单类型 ZF:付款(奖励金) GX:加感谢费(加价) HB:红包 CZ:充值
        switch ($action_type)
		{
		case 'ZF':
		  break;
		case 'GX':

		  break;
		case 'HB':
			$money_list = array(0=>'2',1=>'5',2=>'8',3=>'16');
		  break;
		case 'CZ':
			$money_list = array(0=>'50',1=>'100',2=>'200',3=>'500');
		  break;
		default:
		  $message = "支付方式不支持";
		}

		$list = $this->get_pay_list($user_id,$action_type);

		$data['money_list'] = $money_list;
		$data['payment_list'] = $list;

		GZ_Api::outPut($data);
	}

	/**
	 * 确认订单付款
	 * @return [type] [description]
	 */
	public function confirm_payment(){
		GZ_Api::authToken();
        $user_id	 = _POST("user_id");
        $pay_type	 = _POST("pay_type"); 
        $pay_id		 = _POST("pay_id",0);
        $pay_amount	 = _POST("pay_amount",0);
        $log_id		 = _POST("log_id",0);

		//支付订单类型 ZF:付款(奖励金) GX:加感谢费(加价) HB:红包 CZ:充值
		$message = '';
        switch ($pay_type)
		{
		case 'ZF':
		  	if($log_id==0){
				$message = "事件ID不存在";
			}
		  break;
		case 'GX':
		  	if($pay_amount<=0){
				$message = "输入的金额需大于0";
			}
		  break;
		case 'HB':
			if($pay_amount<=0){
				$message = "输入的红包金额需大于0";
			}
		  break;
		case 'CZ':
			if($pay_amount<=0){
				$message = "充值金额需大于0";
			}
		  break;
		default:
		  $message = "支付方式不支持";
		}

		if(!empty($message)){
			GZ_API::message($message,0);
		}


		if ($pay_id == 1) {//支付宝

			$rescue_log = $this->get_rescue_log($log_id);
			$order_info['order_id']		 = $rescue_log['id'];
			$order_info['order_type']	 = $pay_type; //
			$order_info['order_sn']		 = $rescue_log['order_sn'];
			$order_info['order_surplus'] = $rescue_log['reality_money'];
			$order_info['order_body']	 = '支付救援订单：'.$rescue_log['order_sn'];
			$order_info['order_subject'] = '支付订单消费';

			$alipay_code = $this->get_alipay_code($order_info);
			$data['pay_name'] = '支付宝';
            $data['pay_code'] = $alipay_code;

            GZ_Api::outPut($data);
		}

		if ($pay_id == 2) {//余额支付

			$res_info = $this->account_payment($user_id,$log_id);

			if($res_info['code']>0){
				$this->update_rescue_log($log_id,$pay_id);
				GZ_API::message($res_info['msg'],1);
			}else{

				GZ_API::message($res_info['msg'],0);
			}
		}


	}

	/**
	 * [余额付款]
	 * @return [type] [description]
	 */
	private function account_payment($user_id,$log_id)
	{
		$res_info = array('code' => 0, 'msg'=>'');
		$res_data = $this->get_user_money($user_id);
		$res_rescue = $this->get_rescue_log($log_id);

		if($res_data['user_money']==0){
			$res_info = array('code' => 0, 'msg'=>'余额不足，请充值！');
			return $res_info;
		}

		if($res_rescue['pay_status'] == 1){
			$res_info = array('code' => 0, 'msg'=>'订单已支付，请勿重复提交！');
			return $res_info;
		}

		$reality_money = $res_rescue['reality_money'];
		$res = $this->update_user_account($user_id,$reality_money,0,1,'支付救援奖励');

		if($res){

			$res_info = array('code' => 1, 'msg'=>'支付救援订单成功！');
		}else{
			$res_info = array('code' => 0, 'msg'=>'支付救援订单失败！');
		}

		return $res_info;

	}


	/**
	* 获取支付宝APP 支付签名
	*/
	private function get_alipay_code($order_info){


		
		require_once(GZ_PATH . '/library/alipay/AlipayTradeAppPayRequest.php');
		require_once(GZ_PATH . '/library/alipay/AopClient.php');
		require_once(GZ_PATH . '/library/alipay/config.php');

		$aop = new AopClient();
		$aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
		$aop->appId = $alipay_config['app_id'];
		$aop->rsaPrivateKeyFilePath = $alipay_config['private_key_path'];
		$aop->format = "json";
		$aop->charset = "UTF-8";
		$aop->signType = "RSA2";
		$aop->alipayrsaPublicKey = '请填写支付宝公钥，一行字符串';
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		$request = new AlipayTradeAppPayRequest();
		
		$order_info['order_surplus']='0.01';//test
		
		//构造业务请求参数的集合(订单信息)
		$content = array();
		$content['body']		 = $order_info['order_body'];			
		$content['subject']		 = $order_info['order_subject'];//商品的标题/交易标题/订单标题/订单关键字等
		$content['out_trade_no'] = $order_info['order_sn'];		//商户网站唯一订单号
	    $content['timeout_express'] = '7d';							//该笔订单允许的最晚付款时间
		$content['total_amount'] = $order_info['order_surplus'];	//订单总金额(必须定义成浮点型)
		$content['product_code'] = 'QUICK_MSECURITY_PAY';			//商家和支付宝签约的产品码


		
		$extend_params = array("order_type"=>$order_info['order_type'],"order_id"=>$order_info['order_id']);//回传参数
		$bizextend = json_encode($extend_params);
	    $content['passback_params'] = urlencode($bizextend);//回传参数


		
		$bizcontent = json_encode($content);//$content是biz_content的值,将之转化成字符串
		$request->setNotifyUrl($alipay_config['notify_url']);
		$request->setBizContent($bizcontent);


		//这里和普通的接口调用不同，使用的是sdkExecute
		$response = $aop->sdkExecute($request);

		return $response;

	}


	private function get_pay_list($uid,$action_type=''){

		$res_data = $this->get_user_money($uid);

		$balance_status = 1;
		if($res_data['user_money']=='0.00' || $res_data['user_money']<1){
        	$user_info['explain'] = '余额不足，请充值！';
        	$balance_status = 0;
        }

		$payment[0]['pay_id'] = 1;
		$payment[0]['pay_name'] = '支付宝';
		$payment[0]['pay_desc'] = '推荐有安装支付宝用户使用';
		$payment[0]['pay_status'] = 1;
		$payment[0]['pay_img'] = GZ_Api::get_url('/Mapi/public/images/zfb.png');

		if($action_type!='CZ'){
			$payment[1]['pay_id'] = 2;
			$payment[1]['pay_name'] = '余额支付';
			$payment[1]['pay_desc'] = $res_data['explain'];
			$payment[1]['pay_status'] = $balance_status;
			$payment[1]['pay_img'] = GZ_Api::get_url('/Mapi/public/images/ye.png');
		}

		return $payment;
		
	}


	private function get_rescue_log($log_id){

		$sql = "SELECT * FROM ".$this->table("rescue_log")." WHERE `id`=".$log_id;
        $res_data = $this->getRow($sql);

        return $res_data;
	}



	public function update_rescue_log($id,$pay_type)
	{
		$up_info['status'] = 2;
		$up_info['pay_status'] = 1;
		$up_info['pay_type'] = $pay_type;
		$where = ' id='.$id;
		$this->autoExecute($this->table('rescue_log'), $up_info, 'UPDATA',$where);
	}


	/**
	 * 获取用户账号余额
	 * @param int $uid [用户ID]
	 */
	private function get_user_money($uid)
	{
		$sql = "SELECT `user_money` FROM ".$this->table("users")." WHERE `user_id`=".$uid;
        $res_money = $this->getOne($sql);

        $user_info = array('user_money'=>0,'explain'=>'');
        if($res_money=='0.00' || $res_money<1){

        	$user_info['explain'] = '余额不足，请充值！';
        }else{
			$user_info['user_money'] = $res_money;
        	$user_info['explain'] = '可用余额 '.$res_money .' 元';
        }

        return $user_info;

	}

	/**
	 * 记录帐户变动
	 * 
	 * @param   int     $user_id    用户id
	 * @param   float   $amount     可用余额变动
	 * @param   int     $integral   等级积分变动
	 * @param   int     $change_type变动类型：参见常量文件
	 * @param   string  $change_desc变动说明
	 * @return  void
	 */
	public function update_user_account($user_id,$amount,$integral=0,$type=1,$change_desc=''){

		$user_account['user_id']	 = $user_id;
		$user_account['user_money']	 = $amount;
		$user_account['user_integral'] = $integral;
		$user_account['change_type'] = $type;
		$user_account['change_time'] = time();
		$user_account['change_desc'] = $change_desc;
		
 		/* 插入帐户变动记录 */
		$res = $GLOBALS['db']->autoExecute($GLOBALS['db']->table('user_account'), $user_account, 'INSERT');
		$res_id = $GLOBALS['db']->insert_id();

		if($res_id){

			if($type==1){
				$amount = '-'.$amount;
			}

			/* 更新用户信息 */
		    $sql = "UPDATE " . $GLOBALS['db']->table('users') .
		            " SET user_money = user_money + ('$amount')," .
		            " user_integral = user_integral + ('$integral')" .
		            " WHERE user_id = '$user_id' LIMIT 1";
		    $GLOBALS['db']->query($sql);
		}

		return $res_id;
	}


}


?>